package org.zbclan.bf2.rcon;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegQuery extends ShellCommand {

	// private static final String DELIMITER = "    ";
	// private static final int DELIMITER_LENGTH = DELIMITER.length();

	private static final Pattern VALUE_QUERY_PATTERN = Pattern
			.compile("\r\n.*(?:\r\n    .*    .*    (.*))+\r\n\r\n");
	private static final Pattern SEARCH_QUERY_PATTERN = Pattern
			.compile("(?:\r\n.*)*\r\nEnd of search: \\d match\\(es\\) found\\.\r\n");

	/**
	 * 
	 * @param keyName
	 *            path in the registry
	 * @param valueName
	 *            registry key
	 * @return registry value or null if not found
	 * @throws IOException
	 */
	public String readValue(String keyName, String valueName)
			throws IOException {

		String result;

		// String output = execute("REG QUERY \"" + keyName + "\" /v " +
		// valueName);
		String output = execute("REG", "QUERY", keyName, "/v", valueName);

		Matcher matcher = VALUE_QUERY_PATTERN.matcher(output);
		if (matcher.matches()) {
			result = matcher.group(1);
		} else {
			/*
			 * TODO send back to server for analysis, better through remote
			 * logging
			 */
			result = null;
		}

		// return output.substring(output.lastIndexOf(DELIMITER)
		// + DELIMITER_LENGTH);
		return result;
	}

	public List<String> searchKey(String keyName, String dataPattern)
			throws IOException {

		List<String> result;

		// String output = execute("REG QUERY \"" + keyName + "\" /s /f \""
		// + dataPattern + "\" /k /c /e");
		String output = execute("REG", "QUERY", keyName, "/s", "/f",
				dataPattern, "/k", "/c", "/e");

		Matcher matcher = SEARCH_QUERY_PATTERN.matcher(output);
		if (matcher.matches()) {
			String[] lines = output.split("\r\n");
			result = new ArrayList<String>(lines.length - 2);
			for (int i = 1; i < lines.length - 1; i++) {
				result.add(lines[i]);
			}
		} else {
			/*
			 * TODO send back to server for analysis, better through remote
			 * logging
			 */
			result = null;
		}

		// return output.substring(output.lastIndexOf(DELIMITER)
		// + DELIMITER_LENGTH);
		return result;
	}

	// public String getHomeDir() throws IOException {
	// return readValue(
	// "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
	// "Personal")
	// + "\\Battlefield 2";
	// }
	//
	// public String getInstallDir() throws IOException {
	// return readValue(
	// "HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Games\\Battlefield 2",
	// "InstallDir");
	// }
}